package com.dy.util;

import java.sql.*;

/**
 * @Auther: dy
 * @Date: 2022/2/15 - 02 - 15 - 17:14
 * @Description: com.dy.util
 * @version: 1.0
 */
public class DBUtil {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/db_book?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true";
    private static final String USER = "root";
    private static final String PWD = "root";
    private Connection conn;
    private ResultSet rs;
    private PreparedStatement ps;

    static{
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public Connection getConnection(){
        try {
            conn = DriverManager.getConnection(URL,USER,PWD);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    public ResultSet select(String sql,Object...params) throws SQLException {
        ps = conn.prepareStatement(sql);
        for (int i = 0 ; i < params.length; i++){
            ps.setObject(i+1,params[i]);
        }
        rs = ps.executeQuery();
        return rs;
    }

    public BDResult update(String sql,Object...params) throws SQLException {
        BDResult result = null;
        if (sql.indexOf("insert") > 0){
            ps = conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
        }else{
            ps = conn.prepareStatement(sql);
        }

        for (int i = 0 ; i < params.length; i++){
            ps.setObject(i+1,params[i]);
        }
        int affectRow = 0;
        int addId = 0;
        if (sql.indexOf("insert") > 0){
            affectRow = ps.executeUpdate();
            ResultSet rs = ps.getGeneratedKeys();
            if (rs.next()){
                addId = rs.getInt("1");
                result = new BDResult(affectRow,addId);
            }
        }else{
            affectRow = ps.executeUpdate();
            result = new BDResult(affectRow,addId);
        }
        return result;
    }

    public void close(){
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (ps != null)
                ps.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
